package com.u17;

/**
 * @author u17
 * https://leetcode-cn.com/problems/sqrtx/
 */
public class Solution {

    /**
     * 二分查找
     * @param x
     * @return
     */
    public int mySqrt(int x) {
        // 处理特殊值
        if (x <= 1) {
            return x;
        }

        int start = 0;
        int end = x;
        int result = -1;

        while (start <= end) {
            int mid = (start + end) >> 1;
            // 避免内存溢出，所有使用除法
            if (mid <= x / mid) {
                result = mid;
                start = mid + 1;
            } else {
                end = mid - 1;
            }
        }
        return result;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        int x = 0;
        System.out.println(solution.mySqrt(x));
        System.out.println(Math.sqrt(x));
    }

}
